// pages/myself/balance/Recharge.js
var Zan = require('../../../dist/index.js');
let WxNotificationCenter = require('../../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();

Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    moneytxt:'',
    integralRule:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    this.onPullDownRefresh();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.setData({
      integralRule:[]
    })
    network._post_json(this, api.integralRule, {}, integralsuccess);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  recharge:function(e){
    let money = parseInt(e.detail.value);
    if (money < 1) {
      this.showZanTopTips(2, '充值金额不得少于1元');
      this.setData({
        moneytxt: ''
      })
    }else{
      money = Math.round(money * 100) / 100;
      this.setData({
        moneytxt: money
      })
    }
    
  },
  formSubmit:function(e){

    let money = e.detail.value.money;
    if (money){
      network._post_json(this, api.recharge, { money: money }, success);
    }else{
      this.showZanTopTips(1, "请输入金额！");
    }
    
  }
  
}))
var integralsuccess = function(that,res){
  if(res.data.data){
    that.setData({
      integralRule:res.data.data
    })
  }
}
var success = function(that,res){
  console.log(res.data.data.orderId);
  if (res.data.data.orderId){
    let id = res.data.data.orderId;

    network._post_json(this, api.wxRecharge, { id: id }, wxPaySuccess);
  }
}
// 微信支付结果
var wxPaySuccess = function (that, res) {
  if (res.data.data) {
    wx.requestPayment({
      timeStamp: res.data.data.timeStamp,
      nonceStr: res.data.data.nonceStr,
      package: res.data.data.package,
      signType: res.data.data.signType,
      paySign: res.data.data.paySign,
      success: function (res) {
        wx.showToast({
          title: '充值成功！',
        })
        console.log(res)
        setTimeout(function () {
          WxNotificationCenter.postNotificationName('RechargeRefreshNotification');
          wx.redirectTo({
            url: '/pages/myself/balance/Balance',
          })
        }, 2000);

        
        
      },
      fail: function (res) {
        console.log(res)
      },
    });
  }
}